<template>
  <div class="login-container">
    <!-- 导航栏 -->
    <van-nav-bar
      title="登录"
      left-arrow
      @click-left="$router.back()"
      class="app-nav-bar"
    />
    <!-- 导航栏 -->

    <!-- 登录表单 -->
    <!-- 表单验证，把field放到form中，在submit的时候进行验证 -->
    <!-- 手机号输入框 -->
    <van-form
      @submit="onLogin"
      :show-error="false"
      :show-error-message="false"
      @failed="onFailed"
      validate-first
      ref="login-form"
    >
      <van-field
        v-model="user.mobile"
        icon-prefix="iconfont icon"
        left-icon="shouji"
        placeholder="请输入手机号"
        :rules="formRules.mobile"
        name="mobile"
      />
      <!-- 手机号输入框 -->

      <!-- 验证码输入框 -->
      <van-field
        v-model="user.code"
        clearable
        icon-prefix="iconfont icon"
        left-icon="yanzhengma"
        placeholder="请输入验证码"
        :rules="formRules.code"
        name="code"
      >
        <template #button>
          <van-count-down
            :time="time"
            format="ss s"
            v-if="isCountDownShow"
            @finish="isCountDownShow = false"
          />
          <van-button
            class="send-btn"
            size="small"
            round
            @click.prevent="onSendSms"
            v-else
            :loading="isSendSmsLoading"
          >
            发送验证码
          </van-button>
        </template>
      </van-field>
      <!-- 验证码输入框 -->

      <div class="login-btn-wrap">
        <van-button class="login-btn" type="info" block>登录</van-button>
      </div>
    </van-form>

    <!-- 登录表单 -->
  </div>
</template>

<script>
import { login, sms } from "@/api/user";
import { Toast } from "vant";

export default {
  name: "LoginIndex",
  data() {
    return {
      isSendSmsLoading: false,
      time: 1000 * 60,
      isCountDownShow: false,
      user: {
        mobile: "13589468753",
        code: "246810",
      },
      formRules: {
        mobile: [
          { required: true, message: "请输入手机号" },
          { pattern: /^1[3|5|7|8|9]\d{9}$/, message: "手机号格式错误" },
        ],
        code: [
          { required: true, message: "请输入验证码" },
          { pattern: /\d{6}/, message: "验证码格式错误" },
        ],
      },
    };
  },
  methods: {
    async onLogin() {
      //1.找到数据接口
      //2.封装请求方法
      //3.请求调用登录
      Toast.loading({
        massage: "登陆中",
        //在登录中背景锁定不可点击
        forbidClick: true,
        //持续事件，0不停止
        duration: 0,
      });
      try {
        const res = await login(this.user);
        console.log(res);
        Toast.success("登录成功");
        this.$store.commit("setUser", res.data.data);
        //返回之前页面
        this.$router.back();
      } catch (err) {
        console.log("登陆失败", err);
        Toast.fail("登录失败，手机号或验证码错误");
      }
      //4.处理响应结果
    },
    onFailed(error) {
      if (error.errors[0]) {
        this.$toast({
          message: error.errors[0].message,
          position: "top",
        });
      }
    },
    async onSendSms() {
      try {
        //校验手机号
        await this.$refs["login-form"].validate("mobile");
        //让按钮loading
        this.isSendSmsLoading = true;
        //请求发送验证码
        await sms(this.user.mobile);

        //开始倒计时
        this.isCountDownShow = true;
        //倒计时结束，显示发送按钮
      } catch (err) {
        let message = "";
        if (err && err.response && err.response.status === 429) {
          message = "发送频繁，请稍后重试";
        } else if (err.name === "mobile") {
          message = err.message;
        } else {
          message = "发送失败";
        }

        this.$toast({
          message: message,
          position: "top",
        });
      }
      //无论成功失败都清除loading状态
      this.isSendSmsLoading = false;
    },
  },
};
</script>

<style lang='less' scope>
.login-container {
  .send-btn {
    height: 23px;
    background-color: #ededed;
    .van-button__text {
      font-size: 11px;
      color: #666;
    }
  }
  .login-btn-wrap {
    padding: 26px 16px;
    .login-btn {
      background-color: #6db4fb;
      border: none;
      .van-button__text {
        font-size: 15px;
      }
    }
  }
}
</style>